<?php

namespace App\Http\Controllers\ZHIHU\Systems;

use DB;
use Config;
use Illuminate\Support\Arr;
use Illuminate\Support\Str;
use Illuminate\Http\Request;
use App\Http\Controllers\ZHIHU\ApiController;
use App\Eloqumd\Zhihu\ZhihuSystemConfig;
use App\Eloqumd\Zhihu\ZhihuConfigSource;
use App\Eloqumd\Zhihu\ZhihuSystemNotice;
use App\Eloqumd\Zhihu\ZhihuSystemAdv;
use App\Eloqumd\Zhihu\ZhihuSystemCover;
use App\Eloqumd\Zhihu\ZhihuReportQuestion;
use App\Eloqumd\Zhihu\ZhihuMessage;
use App\Eloqumd\Zhihu\ZhihuUser;
use App\Eloqumd\Zhihu\ZhihuQuestion;
use App\Eloqumd\Zhihu\ZhihuReportAnswer;
use App\Eloqumd\Zhihu\ZhihuAnswer;
use App\Eloqumd\Zhihu\ZhihuPrestige;
use App\Eloqumd\Zhihu\ZhihuUserPrestige;
use App\Eloqumd\Zhihu\ZhihuAdviseFeedback;
use App\Eloqumd\Zhihu\ZhihuFriendLink;
use Carbon\Carbon;
use App\Validate\Zhihu\ZhihuValidator;
use App\Jobs\SystemMessagePublishedNotify;

class SystemsConfigController extends ApiController
{
    // 配置源路由
    static $configSouceRouteVerify = ['edit', 'status', 'remove', 'create', 'list', 'active'];
    // 公告路由
    static $systemNoticeRouteVerify = ['create', 'edit', 'remove', 'list', 'history'];
    // 广告设置
    static $advsSettingRouteVerify = ['list', 'create', 'edit', 'remove'];
    // 封面管理
    static $systemCoverRouteVerify = ['list', 'create', 'edit', 'setting'];
    // 问题举报管理
    static $systemQuestionReportRouteVerify = ['list', 'exam'];
    // 评论举报管理
    static $systemCommentReportRouteVerify = ['list', 'exam'];
    // 声望分值配置
    static $prestigeScoreRouteVerify = ['edit', 'status', 'create', 'list'];
    // 建议反馈管理
    static $feedbackRouteVerify = ['list', 'deal', 'feedback'];
    // 友情链接
    static $friendLinkRouteVerify = ['list', 'create', 'edit', 'status'];

    // 友情链接-list=列表，create=添加，edit=修改,status=启用禁用
    public function friendLink(Request $request, $name)
    {
        if (!in_array($name, static::$friendLinkRouteVerify)) {
            return $this->jsonReturns(99999, trans('zhihu.Illegal-Router-Limited', ['name' => $name]), null, 'verror');
        }

        $param = $request->all();

        $method = "friendLink" . Str::ucfirst($name) . "Operation";

        return $this->$method($param);
    }

    // 友情链接【列表】
    public function friendLinkListOperation($input)
    {
        $page = (int)($input['page'] ?? 1);
        $limit = $input['limit'] ?? $this->limit;
        $offest = ($page - 1) * $limit;
        $status = $input['status'] ?? '';
        // 关键字
        $keyword = $input['keyword'] ?? '';

        $where = null;

        if ($status != '') {
            $where[] = ['status', '=', $status, 'AND'];
        }

        // 快捷搜索
        if ($keyword) {
            $where[] = ['type', 'like', "%{$keyword}%", 'AND'];
        }

        $totalCount = ZhihuFriendLink::where($where)->count();
        $listData = ZhihuFriendLink::where($where)
            ->offset($offest)
            ->limit($limit)
            ->orderBy('created_at', 'desc')
            ->get()
            ->toArray();

        foreach ($listData as $k => $v) {
            $listData[$k]['startdate'] = date('Y-m-d H:i:s', $v['startdate']);
            $listData[$k]['enddate'] = $v['enddate'] == 0 ? '' : date('Y-m-d H:i:s', $v['startdate']);
        }

        $jsonData = ['list' => $listData, 'count' => $totalCount];

        return $this->jsonReturns(10000, $this->success, $jsonData, 'list');
    }

    // 友情链接【添加】
    public function friendLinkCreateOperation($input)
    {
        if (true !== $validateRes = ZhihuValidator::friendLinkCreateOperation($input)) {
            return $this->jsonReturns(50000, $validateRes, null, 'verror');
        }

        DB::beginTransaction();
        try {
            $model = new ZhihuFriendLink;
            $model->tags = $input['tags'];
            $model->name = $input['name'];
            $model->imagesrc = $input['imagesrc'] ?? '';
            $model->links = $input['links'];
            $model->content = $input['content'] ?? '';
            $model->startdate = strtotime($input['startdate']);
            $enddate = $input['enddate'] ?? '';
            $model->enddate = $enddate == '' ? 0 : strtotime($input['enddate']);
            $model->created_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success, null, 'create');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'create');
        }
    }

    // 友情链接【编辑】
    public function friendLinkEditOperation($input)
    {
        if (true !== $validateRes = ZhihuValidator::friendLinkEditOperation($input)) {
            return $this->jsonReturns(50000, $validateRes, null, 'verror');
        }
        
        DB::beginTransaction();
        try {
            $model = ZhihuFriendLink::find($input['id']);
            $model->tags = $input['tags'];
            $model->name = $input['name'];
            $model->imagesrc = $input['imagesrc'] ?? '';
            $model->links = $input['links'];
            $model->content = $input['content'] ?? '';
            $model->startdate = strtotime($input['startdate']);
            $enddate = $input['enddate'] ?? '';
            $model->enddate = $enddate == '' ? 0 : strtotime($input['enddate']);
            $model->status = $input['status'];
            $model->created_at = Carbon::now();
            $model->save();
        
            DB::commit();
        
            return $this->jsonReturns(10000, $this->success, null, 'modify');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'modify');
        }
    }

    // 友情链接【启用禁用】
    public function friendLinkStatusOperation($input)
    {
        $id = $input['id'] ?? 0;
        $status = $input['status'] ?? '';
        if (!$id || $status == '' || !in_array($status, [0, 1])) {
            return $this->jsonReturns(99999, trans('zhihu.The-ID-Can-Not-Be-Empty-Friend'), null, 'verror');
        }

        DB::beginTransaction();
        try {
            $model = ZhihuFriendLink::find($id);
            $model->status = $status;
            $model->updated_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success, null, 'status');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'status');
        }
    }

    // 建议反馈管理-list=列表，deal=处理
    public function feedbackManager(Request $request, $name)
    {
        // 路由校验-路由传参不正确
        if (!in_array($name, static::$feedbackRouteVerify)) {
            return $this->jsonReturns(99999, trans('zhihu.Illegal-Router-Limited', ['name' => $name]), null, 'verror');
        }

        $param = $request->all();

        $method = "feedbackManager" . Str::ucfirst($name) . "Operation";

        return $this->$method($param);
    }

    // 建议反馈管理【列表】
    public function feedbackManagerListOperation($input)
    {
        $page = (int)($input['page'] ?? 1);
        $limit = $input['limit'] ?? $this->limit;
        $offest = ($page - 1) * $limit;
        $user_id = (int)($input['user_id'] ?? 0);
        $status = $input['status'] ?? '';
        // 关键字
        $keyword = $input['keyword'] ?? '';

        $where = null;

        if ($user_id) {
            $where[] = ['user_id', '=', $user_id, 'AND'];
        } else {
            $where[] = ['status', '=', ($status == '' ? 0 : $status), 'AND'];
        }

        // 快捷搜索
        if ($keyword) {
            $where[] = ['type', 'like', "%{$keyword}%", 'AND'];
        }

        $totalCount = ZhihuAdviseFeedback::where($where)->count();
        $listData = ZhihuAdviseFeedback::where($where)
            ->offset($offest)
            ->limit($limit)
            ->orderBy('created_at', 'desc')
            ->get()
            ->toArray();

        foreach ($listData as $k => $v) {
            $user = ZhihuUser::find($v['user_id']);
            $listData[$k]['nickname'] = $user->nickname;
        }

        $jsonData = ['list' => $listData, 'count' => $totalCount];

        return $this->jsonReturns(10000, $this->success, $jsonData, 'list');
    }

    // 建议反馈管理【反馈，添加】
    public function feedbackManagerFeedbackOperation($input)
    {
        if (true !== $validateRes = ZhihuValidator::feedbackManagerFeedbackOperation($input)) {
            return $this->jsonReturns(50000, $validateRes, null, 'verror');
        }

        DB::beginTransaction();
        try {
            $model = new ZhihuAdviseFeedback;
            $model->type = $input['type'];
            $model->content = $input['content'];
            $model->user_id = $this->apiUser['id'];
            $model->created_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, trans('zhihu.Feedback-Created-Success'), null, 'create');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'create');
        }
    }

    // 建议反馈管理【审核】
    public function feedbackManagerDealOperation($input)
    {
        $id = $input['id'] ?? 0;
        $status = $input['status'] ?? '';
        $examMessage = $input['examMessage'] ?? '';
        if (!$id || $status == '' || $examMessage == '') {
            return $this->jsonReturns(99999, trans('zhihu.The-ID-Can-Not-Be-Empty-Friend'), null, 'verror');
        }

        DB::beginTransaction();
        try {
            $model = ZhihuAdviseFeedback::find($id);
            $model->status = $status;
            $model->deal_message = $examMessage;
            $model->updated_at = Carbon::now();
            $model->deal_at = Carbon::now();
            $model->save();

            DB::commit();

            $isRand = false;
            if ($status == 1) {
                $score = (int)ZhihuPrestige::where('preskey', 'feedback')->where('status', 1)->value('score');
                $isRand = true;
                $contentPrestige = trans('zhihu.System-Feedback-Pass-Add-Score-Content', [
                    'score' => $score,
                    'id' => $id,
                    'time' => $model->created_at,
                    'title' => $model->type,
                    'dealtime' => $model->deal_at
                ]);
                $contentMessage = trans('zhihu.Feedback-Message-Exam-Pass-Notify', [
                    'score' => $score,
                    'time' => $model->created_at,
                    'title' => $model->type,
                    'dealtime' => $model->deal_at,
                    'exammsg' => $examMessage
                ]);
            } elseif ($status == 2) {
                $rand = mt_rand(-100, 100);
                if ($rand >= 0) {
                    $score = 1;
                    $isRand = true;
                    $contentPrestige = trans('zhihu.System-Feedback-No-Pass-Add-Score-Content', [
                        'score' => $score,
                        'id' => $id,
                        'time' => $model->created_at,
                        'title' => $model->type,
                        'dealtime' => $model->deal_at
                    ]);
                    $contentMessage = trans('zhihu.Feedback-Message-Exam-No-Pass-Notify', [
                        'score' => $score,
                        'time' => $model->created_at,
                        'title' => $model->type,
                        'dealtime' => $model->deal_at,
                        'exammsg' => $examMessage
                    ]);
                } else {
                    $contentMessage = trans('zhihu.Feedback-Message-Exam-No-Pass-Notify2', [
                        'time' => $model->created_at,
                        'title' => $model->type,
                        'dealtime' => $model->deal_at,
                        'exammsg' => $examMessage
                    ]);
                }
            }
            if ($isRand) {
                ZhihuUserPrestige::insert([
                    'user_id' => $model->user_id,
                    'title' => trans('zhihu.System-Feedback-Prestige-Title', ['title' => $model->type]),
                    'conent' => $contentPrestige,
                    'types' => 0,
                    'score' => $score,
                    'created_at' => Carbon::now()
                ]);
            }

            $msg = new ZhihuMessage;
            $msg->from_id = $this->apiUser['id'];
            $msg->from_name = $this->apiUser['nickname'];
            $msg->to_id = $model->user_id;
            $msg->content = $contentMessage;
            $msg->status = 0;
            $msg->is_system = 1;
            $msg->created_at = Carbon::now();
            $msg->save();

            // socket通知
            $job = (new SystemMessagePublishedNotify([
                'channelType' => 'feedback',
                'message' => $msg->content,
                'title' => trans('zhihu.System-Feedback-Title'),
                'data' => $msg->toArray()
            ]));
            $this->dispatch($job);

            return $this->jsonReturns(10000, $this->success, null, 'feedback');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'feedback');
        }
    }

    // 声望分值配置-list=列表,edit=修改,status=启用禁用,create=添加
    public function prestigeScore(Request $request, $name)
    {
        // 路由校验-路由传参不正确
        if (!in_array($name, static::$prestigeScoreRouteVerify)) {
            return $this->jsonReturns(99999, trans('zhihu.Illegal-Router-Limited', ['name' => $name]), null, 'verror');
        }

        $param = $request->all();

        $method = "prestigeScore" . Str::ucfirst($name) . "Operation";

        return $this->$method($param);
    }

    // 声望分值配置-列表
    public function prestigeScoreListOperation($input)
    {
        $page = (int)($input['page'] ?? 1);
        $limit = $input['limit'] ?? $this->limit;
        $offest = ($page - 1) * $limit;
        // 关键字
        $keyword = $input['keyword'] ?? '';

        $where = null;
        // 快捷搜索
        if ($keyword) {
            $where[] = ['preskey', 'like', "%{$keyword}%", 'AND'];
            $where[] = ['name', 'like', "%{$keyword}%", 'OR'];
        }

        $totalCount = ZhihuPrestige::where($where)->count();
        $listData = ZhihuPrestige::where($where)
            ->offset($offest)
            ->limit($limit)
            ->get()
            ->toArray();

        $jsonData = ['list' => $listData, 'count' => $totalCount];

        return $this->jsonReturns(10000, $this->success, $jsonData, 'list');
    }

    // 声望分值配置【添加】
    public function prestigeScoreCreateOperation($input)
    {
        if (true !== $validateRes = ZhihuValidator::prestigeScoreCreateOperation($input)) {
            return $this->jsonReturns(50000, $validateRes, null, 'verror');
        }

        DB::beginTransaction();
        try {
            $model = new ZhihuPrestige;
            $model->preskey = strtolower($input['preskey']);
            $model->name = $input['name'];
            $model->score = (int)$input['score'];
            $model->status = (int)$input['status'];
            $model->created_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success, null, 'create');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'create');
        }
    }

    // 声望分值配置【修改】
    public function prestigeScoreEditOperation($input)
    {
        if (true !== $validateRes = ZhihuValidator::prestigeScoreEditOperation($input)) {
            return $this->jsonReturns(50000, $validateRes, null, 'verror');
        }

        DB::beginTransaction();
        try {
            $model = ZhihuPrestige::find($input['id']);
            $model->preskey = strtolower($input['preskey']);
            $model->name = $input['name'];
            $model->score = (int)$input['score'];
            $model->status = (int)$input['status'];
            $model->updated_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success, null, 'modify');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'modify');
        }
    }

    // 声望分值配置【启用禁用】
    public function prestigeScoreStatusOperation($input)
    {
        $id = $input['id'] ?? 0;
        $status = $input['status'] ?? '';
        if (!$id || $status == '' || !in_array($status, [0, 1])) {
            return $this->jsonReturns(99999, trans('zhihu.The-ID-Can-Not-Be-Empty-Friend'), null, 'verror');
        }

        DB::beginTransaction();
        try {
            $model = ZhihuPrestige::find($id);
            $model->status = $status;
            $model->updated_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success, null, 'status');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'status');
        }
    }

    // 评论举报管理-list=列表，exam=审核
    public function reportCommentManager(Request $request, $name)
    {
        // 路由校验-路由传参不正确
        if (!in_array($name, static::$systemCommentReportRouteVerify)) {
            return $this->jsonReturns(99999, trans('zhihu.Illegal-Router-Limited', ['name' => $name]), null, 'verror');
        }

        $param = $request->all();

        $method = "reportCommentManager" . Str::ucfirst($name) . "Operation";

        return $this->$method($param);
    }

    // 评论举报管理【列表】
    public function reportCommentManagerListOperation($input)
    {
        $page = (int)($input['page'] ?? 1);
        $limit = $input['limit'] ?? $this->limit;
        $offest = ($page - 1) * $limit;
        $status = $input['status'] ?? '';
        // 关键字
        $keyword = $input['keyword'] ?? '';

        $where = null;

        $where[] = ['status', '=', ($status == '' ? 0 : $status), 'AND'];

        // 快捷搜索
        if ($keyword) {
            $where[] = ['question_title', 'like', "%{$keyword}%", 'AND'];
        }

        $totalCount = ZhihuReportAnswer::where($where)->count();
        $listData = ZhihuReportAnswer::where($where)
            ->offset($offest)
            ->limit($limit)
            ->orderBy('created_at', 'desc')
            ->get()
            ->toArray();

        $jsonData = ['list' => $listData, 'count' => $totalCount];

        return $this->jsonReturns(10000, $this->success, $jsonData, 'list');
    }

    // 评论举报管理【审核】
    public function reportCommentManagerExamOperation($input)
    {
        $id = $input['id'] ?? 0;
        $status = $input['status'] ?? '';
        $examMessage = $input['examMessage'] ?? '';
        if (!$id || $status == '' || $examMessage == '') {
            return $this->jsonReturns(99999, trans('zhihu.The-ID-Can-Not-Be-Empty-Friend'), null, 'verror');
        }

        DB::beginTransaction();
        try {
            $model = ZhihuReportAnswer::find($id);
            $model->status = $status;
            $model->report_exam_message = $examMessage;
            $model->updated_at = Carbon::now();
            $model->examed_at = Carbon::now();
            $model->save();

            DB::commit();

            $report = ZhihuUser::find($model->report_user_id);
            $bereport = ZhihuUser::find($model->answer_user_id);
            // 举报人及被举报人socket通知及信息发送
            if ($status == 1) {
                $score2 = (int)ZhihuPrestige::where('preskey', 'bereport')->where('status', 1)->value('score');
                $score = (int)ZhihuPrestige::where('preskey', 'report')->where('status', 1)->value('score');
                $asw = ZhihuAnswer::find($model->answer_id);
                $question = ZhihuQuestion::find($model->question_id);
                $msg2 = new ZhihuMessage;
                $msg2->from_id = $this->apiUser['id'];
                $msg2->from_name = $this->apiUser['nickname'];
                $msg2->to_id = $model->answer_user_id;
                $msg2->content = trans('zhihu.Report-Comment-Waring-Notify', [
                    'name' => $bereport->nickname,
                    'time' => $asw->created_at,
                    'title' => $model->question_title,
                    'content' => $model->report_type,
                ]);
                $msg2->status = 0;
                $msg2->is_system = 1;
                $msg2->created_at = Carbon::now();
                $msg2->save();

                // socket通知
                $job = (new SystemMessagePublishedNotify([
                    'channelType' => 'report',
                    'message' => $msg2->content,
                    'data' => $msg2->toArray()
                ]));
                $this->dispatch($job);

                ZhihuUserPrestige::insert([
                    'user_id' => $model->answer_user_id,
                    'title' => trans('zhihu.System-Answer-Bereport-Title', [
                        'cate' => Config::get('api.zhihu_question_type')[$question->cates],
                        'title' => $question->title,
                    ]),
                    'conent' => trans('zhihu.System-Answer-Bereport-Add-Score-Content', [
                        'score' => $score2,
                        'cate' => Config::get('api.zhihu_question_type')[$question->cates],
                        'id' => $model->answer_id,
                        'name' => $bereport->nickname,
                        'time' => $asw->created_at,
                        'title' => $model->question_title,
                        'content' => $model->report_type,
                    ]),
                    'types' => 1,
                    'score' => $score2,
                    'created_at' => Carbon::now()
                ]);

                $msg = new ZhihuMessage;
                $msg->from_id = $this->apiUser['id'];
                $msg->from_name = $this->apiUser['nickname'];
                $msg->to_id = $model->report_user_id;
                $msg->content = trans('zhihu.Report-Comment-Exam-Pass-Notify', [
                    'name' => $report->nickname,
                    'time' => $model->created_at,
                    'title' => $model->question_title,
                    'exammsg' => $examMessage,
                    'bereport' => $bereport->nickname
                ]);
                $msg->status = 0;
                $msg->is_system = 1;
                $msg->created_at = Carbon::now();
                $msg->save();

                // socket通知
                $job = (new SystemMessagePublishedNotify([
                    'channelType' => 'report',
                    'message' => $msg->content,
                    'title' => trans('zhihu.System-Report-Exam-Result-Notify-Title'),
                    'data' => $msg->toArray()
                ]));
                $this->dispatch($job);

                ZhihuUserPrestige::insert([
                    'user_id' => $model->report_user_id,
                    'title' => trans('zhihu.System-Answer-Report-Title', [
                        'cate' => Config::get('api.zhihu_question_type')[$question->cates],
                        'title' => $question->title,
                    ]),
                    'conent' => trans('zhihu.System-Answer-Report-Add-Score-Content', [
                        'score' => $score,
                        'cate' => Config::get('api.zhihu_question_type')[$question->cates],
                        'id' => $model->question_id,
                        'name' => $report->nickname,
                        'time' => $model->created_at,
                        'title' => $model->question_title,
                        'exammsg' => $examMessage,
                        'bereport' => $bereport->nickname
                    ]),
                    'types' => 0,
                    'score' => $score,
                    'created_at' => Carbon::now()
                ]);
            // 举报人socket通知及信息发送
            } elseif ($status == 2) {
                $msg = new ZhihuMessage;
                $msg->from_id = $this->apiUser['id'];
                $msg->from_name = $this->apiUser['nickname'];
                $msg->to_id = $model->report_user_id;
                $msg->content = trans('zhihu.Report-Comment-Exam-Reback-Notify', [
                    'name' => $report->nickname,
                    'time' => $model->created_at,
                    'title' => $model->question_title,
                    'exammsg' => $examMessage,
                    'bereport' => $bereport->nickname
                ]);
                $msg->status = 0;
                $msg->is_system = 1;
                $msg->created_at = Carbon::now();
                $msg->save();

                // socket通知
                $job = (new SystemMessagePublishedNotify([
                    'channelType' => 'report',
                    'message' => $msg->content,
                    'title' => trans('zhihu.System-Report-Exam-Result-Notify-Title'),
                    'data' => $msg->toArray()
                ]));
                $this->dispatch($job);
            }

            return $this->jsonReturns(10000, $this->success, null, 'exam');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'exam');
        }
    }

    // 问题举报管理-list=列表，exam=审核
    public function reportManager(Request $request, $name)
    {
        // 路由校验-路由传参不正确
        if (!in_array($name, static::$systemQuestionReportRouteVerify)) {
            return $this->jsonReturns(99999, trans('zhihu.Illegal-Router-Limited', ['name' => $name]), null, 'verror');
        }

        $param = $request->all();

        $method = "reportManager" . Str::ucfirst($name) . "Operation";

        return $this->$method($param);
    }

    // 举报管理【列表】
    public function reportManagerListOperation($input)
    {
        $page = (int)($input['page'] ?? 1);
        $limit = $input['limit'] ?? $this->limit;
        $offest = ($page - 1) * $limit;
        $status = $input['status'] ?? '';
        // 关键字
        $keyword = $input['keyword'] ?? '';

        $where = null;

        $where[] = ['status', '=', ($status == '' ? 0 : $status), 'AND'];

        // 快捷搜索
        if ($keyword) {
            $where[] = ['question_title', 'like', "%{$keyword}%", 'AND'];
        }

        $totalCount = ZhihuReportQuestion::where($where)->count();
        $listData = ZhihuReportQuestion::where($where)
            ->offset($offest)
            ->limit($limit)
            ->orderBy('created_at', 'desc')
            ->get()
            ->toArray();

        $jsonData = ['list' => $listData, 'count' => $totalCount];

        return $this->jsonReturns(10000, $this->success, $jsonData, 'list');
    }

    // 举报管理【审核】
    public function reportManagerExamOperation($input)
    {
        $id = $input['id'] ?? 0;
        $status = $input['status'] ?? '';
        $examMessage = $input['examMessage'] ?? '';
        if (!$id || $status == '' || $examMessage == '') {
            return $this->jsonReturns(99999, trans('zhihu.The-ID-Can-Not-Be-Empty-Friend'), null, 'verror');
        }

        DB::beginTransaction();
        try {

            $model = ZhihuReportQuestion::find($id);
            $model->status = $status;
            $model->report_exam_message = $examMessage;
            $model->updated_at = Carbon::now();
            $model->examed_at = Carbon::now();
            $model->save();

            DB::commit();

            $report = ZhihuUser::find($model->report_user_id);
            // 举报人及被举报人socket通知及信息发送
            if ($status == 1) {
                $score2 = (int)ZhihuPrestige::where('preskey', 'bereport')->where('status', 1)->value('score');
                $score = (int)ZhihuPrestige::where('preskey', 'report')->where('status', 1)->value('score');

                // 被举报审核通过
                $bereport = ZhihuUser::find($model->question_user_id);
                $question = ZhihuQuestion::find($model->question_id);
                $msg2 = new ZhihuMessage;
                $msg2->from_id = $this->apiUser['id'];
                $msg2->from_name = $this->apiUser['nickname'];
                $msg2->to_id = $model->question_user_id;
                $msg2->content = trans('zhihu.Report-Waring-Notify', [
                    'name' => $bereport->nickname,
                    'time' => $question->created_at,
                    'title' => $model->question_title,
                    'content' => $model->report_type,
                ]);
                $msg2->status = 0;
                $msg2->is_system = 1;
                $msg2->created_at = Carbon::now();
                $msg2->save();

                // socket通知
                $job = (new SystemMessagePublishedNotify([
                    'channelType' => 'report',
                    'message' => $msg2->content,
                    // 'title' => trans('zhihu.System-Report-Exam-Result-Notify-Title'),
                    'data' => $msg2->toArray()
                ]));
                $this->dispatch($job);

                ZhihuUserPrestige::insert([
                    'user_id' => $model->question_user_id,
                    'title' => trans('zhihu.System-Question-Bereport-Title', [
                        'cate' => Config::get('api.zhihu_question_type')[$question->cates],
                        'title' => $question->title,
                    ]),
                    'conent' => trans('zhihu.System-Question-Bereport-Add-Score-Content', [
                        'score' => $score2,
                        'cate' => Config::get('api.zhihu_question_type')[$question->cates],
                        'id' => $model->question_id,
                        'name' => $bereport->nickname,
                        'time' => $question->created_at,
                        'title' => $model->question_title,
                        'content' => $model->report_type,
                    ]),
                    'types' => 1,
                    'score' => $score2,
                    'created_at' => Carbon::now()
                ]);

                // 举报人反馈
                $msg = new ZhihuMessage;
                $msg->from_id = $this->apiUser['id'];
                $msg->from_name = $this->apiUser['nickname'];
                $msg->to_id = $model->report_user_id;
                $msg->content = trans('zhihu.Report-Exam-Pass-Notify', [
                    'name' => $report->nickname,
                    'time' => $model->created_at,
                    'title' => $model->question_title,
                    'exammsg' => $examMessage
                ]);
                $msg->status = 0;
                $msg->is_system = 1;
                $msg->created_at = Carbon::now();
                $msg->save();

                // socket通知
                $job = (new SystemMessagePublishedNotify([
                    'channelType' => 'report',
                    'message' => $msg->content,
                    'title' => trans('zhihu.System-Report-Exam-Result-Notify-Title'),
                    'data' => $msg->toArray()
                ]));
                $this->dispatch($job);

                ZhihuUserPrestige::insert([
                    'user_id' => $model->report_user_id,
                    'title' => trans('zhihu.System-Question-Report-Title', [
                        'cate' => Config::get('api.zhihu_question_type')[$question->cates],
                        'title' => $question->title,
                    ]),
                    'conent' => trans('zhihu.System-Question-Report-Add-Score-Content', [
                        'score' => $score,
                        'cate' => Config::get('api.zhihu_question_type')[$question->cates],
                        'id' => $model->question_id,
                        'name' => $report->nickname,
                        'time' => $model->created_at,
                        'title' => $model->question_title,
                        'exammsg' => $examMessage
                    ]),
                    'types' => 0,
                    'score' => $score,
                    'created_at' => Carbon::now()
                ]);
            // 举报人socket通知及信息发送
            } elseif ($status == 2) {
                $msg = new ZhihuMessage;
                $msg->from_id = $this->apiUser['id'];
                $msg->from_name = $this->apiUser['nickname'];
                $msg->to_id = $model->report_user_id;
                $msg->content = trans('zhihu.Report-Exam-Reback-Notify', [
                    'name' => $report->nickname,
                    'time' => $model->created_at,
                    'title' => $model->question_title,
                    'exammsg' => $examMessage
                ]);
                $msg->status = 0;
                $msg->is_system = 1;
                $msg->created_at = Carbon::now();
                $msg->save();

                // socket通知
                $job = (new SystemMessagePublishedNotify([
                    'channelType' => 'report',
                    'message' => $msg->content,
                    'title' => trans('zhihu.System-Report-Exam-Result-Notify-Title'),
                    'data' => $msg->toArray()
                ]));
                $this->dispatch($job);
            }

            return $this->jsonReturns(10000, $this->success, null, 'exam');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'exam');
        }
    }

    // 封面管理-list=列表，create=添加，edit=修改，setting=设置为封面
    public function coverManager(Request $request, $name)
    {
        // 路由校验-路由传参不正确
        if (!in_array($name, static::$systemCoverRouteVerify)) {
            return $this->jsonReturns(99999, trans('zhihu.Illegal-Router-Limited', ['name' => $name]), null, 'verror');
        }

        $param = $request->all();

        $method = "systemCover" . Str::ucfirst($name) . "Operation";

        return $this->$method($param);
    }

    // 封面管理【列表】
    public function systemCoverListOperation($input)
    {
        $page = (int)($input['page'] ?? 1);
        $limit = $input['limit'] ?? $this->limit;
        $offest = ($page - 1) * $limit;
        // 关键字
        $keyword = $input['keyword'] ?? '';

        $where = null;
        // 快捷搜索
        if ($keyword) {
            $where[] = ['title', 'like', "%{$keyword}%", 'AND'];
        }

        $totalCount = ZhihuSystemCover::where($where)->count();
        $listData = ZhihuSystemCover::where($where)
            ->offset($offest)
            ->limit($limit)
            ->orderBy('created_at', 'desc')
            ->get()
            ->toArray();

        foreach ($listData as $k => $v) {
            $listData[$k]['start_date'] = ($v['start_date'] == 0 ? '' : date('Y-m-d H:i:s', $v['start_date']));
            $listData[$k]['end_date'] = ($v['end_date'] == 0 ? '' : date('Y-m-d H:i:s', $v['end_date']));
        }

        $jsonData = ['list' => $listData, 'count' => $totalCount];

        return $this->jsonReturns(10000, $this->success, $jsonData, 'list');
    }

    // 封面管理【添加】
    public function systemCoverCreateOperation($input)
    {
        if (true !== $validateRes = ZhihuValidator::systemCoverCreateOperation($input)) {
            return $this->jsonReturns(50000, $validateRes, null, 'verror');
        }

        DB::beginTransaction();
        try {
            $model = new ZhihuSystemCover;
            $model->title = $input['title'];
            $model->description = $input['description'] ?? '';
            $model->coverimg = $input['coverimg'];

            // 有且只有起始和截止都存在才会入库
            if ($input['start_date'] && $input['end_date']) {
                $model->start_date = strtotime($input['start_date']);
                $model->end_date = strtotime($input['end_date']);
            }

            $model->created_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success, null, 'create');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'create');
        }
    }

    // 封面管理【修改】
    public function systemCoverEditOperation($input)
    {
        if (true !== $validateRes = ZhihuValidator::systemCoverEditOperation($input)) {
            return $this->jsonReturns(50000, $validateRes, null, 'verror');
        }

        DB::beginTransaction();
        try {
            $model = ZhihuSystemCover::find($input['id']);
            $model->title = $input['title'];
            $model->description = $input['description'] ?? '';
            $model->coverimg = $input['coverimg'];

            // 有且只有起始和截止都存在才会入库
            if ($input['start_date'] && $input['end_date']) {
                $model->start_date = strtotime($input['start_date']);
                $model->end_date = strtotime($input['end_date']);
            } else {
                $model->start_date = 0;
                $model->end_date = 0;
            }

            $model->created_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success, null, 'modify');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'modify');
        }
    }

    // 封面管理【设置】
    public function systemCoverSettingOperation($input)
    {
        $id = $input['id'] ?? 0;
        $status = $input['status'] ?? '';
        if (!$id || $status == '') {
            return $this->jsonReturns(99999, trans('zhihu.The-ID-Can-Not-Be-Empty-Friend'), null, 'verror');
        }

        DB::beginTransaction();
        try {
            // 将其他设置置为取消
            // 更新最新公告为历史
            ZhihuSystemCover::where('status', 1)->update([
                'status' => 0,
                'updated_at' => Carbon::now()
            ]);

            $model = ZhihuSystemCover::find($id);
            $model->status = $status;
            $model->updated_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success, null, 'status');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'status');
        }
    }

    // 广告设置-list=列表，create=添加，remove=删除，edit=修改
    public function advsSetting(Request $request, $name)
    {
        // 路由校验-路由传参不正确
        if (!in_array($name, static::$systemNoticeRouteVerify)) {
            return $this->jsonReturns(99999, trans('zhihu.Illegal-Router-Limited', ['name' => $name]), null, 'verror');
        }

        $param = $request->all();

        $method = "advsSetting" . Str::ucfirst($name) . "Operation";

        return $this->$method($param);
    }

    // 广告设置【列表】
    public function advsSettingListOperation($input)
    {
        $page = (int)($input['page'] ?? 1);
        $limit = $input['limit'] ?? $this->limit;
        $offest = ($page - 1) * $limit;
        // 关键字
        $keyword = $input['keyword'] ?? '';
        // 筛选广告类型，all=所有，passed=过期，activiting=生效中，waiting=等待中
        $style = $input['style'] ?? 'all';
        // 广告类型
        $type = $input['type'] ?? '';
        // 日期
        $searchdate = $input['searchdate'] ?? [];

        $where = null;
        $where[] = ['status', '=', 1, 'AND'];
        if ($type) {
            $where[] = ['type', '=', $type, 'AND'];
        }
        if ($searchdate) {
            $where[] = ['start_date', '<=', strtotime($searchdate[0]), 'AND'];
            $where[] = ['end_date', '<=', strtotime($searchdate[1]), 'AND'];
        }
        // 快捷搜索
        if ($keyword) {
            $where[] = ['title', 'like', "%{$keyword}%", 'AND'];
            $where[] = ['advcomname', 'like', "%{$keyword}%", 'OR'];
        }

        $currentTime = time();

        switch ($style) {
            case 'passed':
                $where[] = ['end_date', '<', $currentTime, 'AND'];
                break;
            case 'activiting':
                $where[] = ['end_date', '>', $currentTime, 'AND'];
                $where[] = ['start_date', '<=', $currentTime, 'AND'];
                break;
            case 'waiting':
                $where[] = ['start_date', '>', $currentTime, 'AND'];
                break;
            default:
                break;
        }

        $totalCount = ZhihuSystemAdv::where($where)->count();
        $listData = ZhihuSystemAdv::where($where)
            ->offset($offest)
            ->limit($limit)
            ->orderBy('created_at', 'desc')
            ->get()
            ->toArray();

        foreach ($listData as $k => $v) {
            $listData[$k]['start_date'] = date('Y-m-d H:i:s', $v['start_date']);
            $listData[$k]['end_date'] = date('Y-m-d H:i:s', $v['end_date']);
        }

        $jsonData = ['list' => $listData, 'count' => $totalCount];

        return $this->jsonReturns(10000, $this->success, $jsonData, 'list');
    }

    // 广告设置【添加】
    public function advsSettingCreateOperation($input)
    {
        if (true !== $validateRes = ZhihuValidator::advsSettingCreateOperation($input)) {
            return $this->jsonReturns(50000, $validateRes, null, 'verror');
        }

        DB::beginTransaction();
        try {
            $model = new ZhihuSystemAdv;
            $model->advcomname = $input['advcomname'];
            $model->advcomcontactname = $input['advcomcontactname'];
            $model->advcomcontact = $input['advcomcontact'];
            $model->title = $input['title'];
            $model->description = $input['description'] ?? '';
            $model->imageurl = $input['imageurl'] ?? '';
            $model->imagelink = $input['imagelink'] ?? '';
            $model->blanklinkurl = $input['blanklinkurl'] ?? '';
            $model->orderby = $input['orderby'] ?? '10';
            $model->type = $input['type'];
            $model->start_date = strtotime($input['start_date']);
            $model->end_date = strtotime($input['end_date']);
            $model->created_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success, null, 'create');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'create');
        }
    }

    // 广告设置【修改】
    public function advsSettingEditOperation($input)
    {
        if (true !== $validateRes = ZhihuValidator::advsSettingEditOperation($input)) {
            return $this->jsonReturns(50000, $validateRes, null, 'verror');
        }

        DB::beginTransaction();
        try {
            $model = ZhihuSystemAdv::find($input['id']);
            $model->advcomname = $input['advcomname'];
            $model->advcomcontactname = $input['advcomcontactname'];
            $model->advcomcontact = $input['advcomcontact'];
            $model->title = $input['title'];
            $model->description = $input['description'] ?? '';
            $model->imageurl = $input['imageurl'] ?? '';
            $model->imagelink = $input['imagelink'] ?? '';
            $model->blanklinkurl = $input['blanklinkurl'] ?? '';
            $model->orderby = $input['orderby'] ?? '10';
            $model->type = $input['type'];
            $model->start_date = strtotime($input['start_date']);
            $model->end_date = strtotime($input['end_date']);
            $model->updated_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success, null, 'modfiy');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'modify');
        }
    }

    // 广告设置【删除】
    public function advsSettingRemoveOperation($input)
    {
        $id = $input['id'] ?? 0;
        if (!$id) {
            return $this->jsonReturns(99999, trans('zhihu.The-ID-Can-Not-Be-Empty-Friend'), null, 'verror');
        }

        DB::beginTransaction();
        try {
            $model = ZhihuSystemAdv::find($id);
            $model->status = 0;
            $model->updated_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success, null, 'delete');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'delete');
        }
    }

    // 系统公告【添加，修改，删除，列表，历史列表】入口
    public function systemNotice(Request $request, $name)
    {
        // 路由校验-路由传参不正确
        if (!in_array($name, static::$systemNoticeRouteVerify)) {
            return $this->jsonReturns(99999, trans('zhihu.Illegal-Router-Limited', ['name' => $name]), null, 'verror');
        }

        $param = $request->all();

        $method = "notice" . Str::ucfirst($name) . "Operation";

        return $this->$method($param);
    }

    // 系统公告【添加】
    public function noticeCreateOperation($input)
    {
        $content = $input['content'] ?? '';
        if (!$content) {
            return $this->jsonReturns(99999, trans('zhihu.The-Notice-Content-Can-Not-Be-Empty-Friend'), null, 'verror');
        }
        if (strlen($content) > 500) {
            return $this->jsonReturns(99999, trans('zhihu.The-Notice-Content-Can-Not-More-Than-Point-Character', ['limitVal' => 500]), null, 'verror');
        }

        DB::beginTransaction();
        try {
            // 更新最新公告为历史
            ZhihuSystemNotice::where('status', 1)->update([
                'status' => 0,
                'updated_at' => Carbon::now()
            ]);

            $model = new ZhihuSystemNotice;
            $model->content = $content;
            $model->created_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success, null, 'create');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'create');
        }
    }

    // 系统公告【修改】
    public function noticeEditOperation($input)
    {
        $id = $input['id'] ?? 0;
        $content = $input['content'] ?? '';
        if (!$id) {
            return $this->jsonReturns(99999, trans('zhihu.The-ID-Can-Not-Be-Empty-Friend'), null, 'verror');
        }
        if (!$content) {
            return $this->jsonReturns(99999, trans('zhihu.The-Notice-Content-Can-Not-Be-Empty-Friend'), null, 'verror');
        }
        if (strlen($content) > 500) {
            return $this->jsonReturns(99999, trans('zhihu.The-Notice-Content-Can-Not-More-Than-Point-Character', ['limitVal' => 500]), null, 'verror');
        }

        DB::beginTransaction();
        try {
            $model = ZhihuSystemNotice::find($id);
            $model->content = $content;
            $model->updated_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success, null, 'modify');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'modify');
        }
    }

    // 系统公告【删除-移除-作废】
    public function noticeRemoveOperation($input)
    {
        $id = $input['id'] ?? 0;
        if (!$id) {
            return $this->jsonReturns(99999, trans('zhihu.The-ID-Can-Not-Be-Empty-Friend'), null, 'verror');
        }

        DB::beginTransaction();
        try {
            $model = ZhihuSystemNotice::find($id);
            $model->status = 0;
            $model->updated_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success, null, 'delete');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'delete');
        }
    }

    // 系统公告【列表】
    public function noticeListOperation($input)
    {
        $page = (int)($input['page'] ?? 1);
        $limit = $input['limit'] ?? $this->limit;
        $offest = ($page - 1) * $limit;
        // 是否包含历史
        $history = $input['history'] ?? 0;

        $where = null;
        // 快捷搜索-问题标题
        if (!$history) {
            $where[] = ['status', '=', 1, 'AND'];
        }

        $totalCount = ZhihuSystemNotice::where($where)->count();
        $listData = ZhihuSystemNotice::where($where)
            ->offset($offest)
            ->limit($limit)
            ->orderBy('created_at', 'desc')
            ->get()
            ->toArray();

        $jsonData = ['list' => $listData, 'count' => $totalCount];

        return $this->jsonReturns(10000, $this->success, $jsonData, 'list');
    }

    // 系统公告【历史列表】
    /* public function noticeHistoryOperation($input)
    {
        $page = (int)($input['page'] ?? 1) - 1;
        $limit = $input['limit'] ?? $this->limit;

        $totalCount = ZhihuSystemNotice::where('status', 0)->count();
        $listData = ZhihuSystemNotice::where('status', 0)
            ->offset($page)
            ->limit($limit)
            ->orderBy('created_at', 'desc')
            ->get()
            ->toArray();

        $jsonData = ['list' => $listData, 'count' => $totalCount];

        return $this->jsonReturns(10000, $this->success, $jsonData);
    } */

    // 设置配置源【添加，修改，删除，启用禁用，列表】入口
    public function configSource(Request $request, $name)
    {
        // 路由校验-路由传参不正确
        if (!in_array($name, static::$configSouceRouteVerify)) {
            return $this->jsonReturns(99999, trans('zhihu.Illegal-Router-Limited', ['name' => $name]), null, 'verror');
        }

        $param = $request->all();

        $method = "source" . Str::ucfirst($name) . "Config";

        return $this->$method($param);
    }

    // 获取有效配置源
    public function sourceActiveConfig($input)
    {
        $listData = ZhihuConfigSource::where('status', 1)
            ->where('is_removed', 0)
            ->where('is_system', 1)
            ->get()
            ->toArray();

        /* foreach ($listData as $k => $v) {
            $listData[$k]['key_name'] = ucfirst($v['key_name']);
        } */

        $jsonData = ['list' => $listData];

        return $this->jsonReturns(10000, $this->success, $jsonData, 'list');
    }

    // 设置配置源【修改】
    public function sourceEditConfig($input)
    {
        if (true !== $validateRes = ZhihuValidator::sourceEditConfig($input)) {
            return $this->jsonReturns(50000, $validateRes, null, 'verror');
        }

        DB::beginTransaction();
        try {
            $model = ZhihuConfigSource::find($input['id']);
            $model->key_name = $input['key_name'];
            $model->key_field = $input['key_field'];
            $model->key_title = $input['key_title'];
            $model->status = $input['status'];
            $model->is_system = $input['is_system'];
            $model->updated_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success, null, 'modify');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'modify');
        }
    }

    // 设置配置源【启用禁用】
    public function sourceStatusConfig($input)
    {
        $id = $input['id'] ?? 0;
        $status = $input['status'] ?? '';
        if (!$id || $status == '' || !in_array($status, [0, 1])) {
            return $this->jsonReturns(99999, trans('zhihu.The-ID-Can-Not-Be-Empty-Friend'), null, 'verror');
        }

        DB::beginTransaction();
        try {
            $model = ZhihuConfigSource::find($id);
            $model->status = $status;
            $model->updated_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success, null, 'status');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'status');
        }
    }

    // 设置配置源【删除】
    public function sourceRemoveConfig($input)
    {
        $id = $input['id'] ?? 0;
        if (!$id) {
            return $this->jsonReturns(99999, trans('zhihu.The-ID-Can-Not-Be-Empty-Friend'), null, 'verror');
        }

        DB::beginTransaction();
        try {
            $model = ZhihuConfigSource::find($id);
            $model->status = 0;
            $model->is_removed = 1;
            $model->updated_at = Carbon::now();
            $model->removed_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success, null, 'delete');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'delete');
        }
    }

    // 设置配置源【添加】
    public function sourceCreateConfig($input)
    {
        if (true !== $validateRes = ZhihuValidator::sourceCreateConfig($input)) {
            return $this->jsonReturns(50000, $validateRes, null, 'verror');
        }

        DB::beginTransaction();
        try {
            $model = new ZhihuConfigSource;
            $model->key_name = $input['key_name'];
            $model->key_field = $input['key_field'];
            $model->key_title = $input['key_title'];
            $model->is_system = $input['is_system'];
            $model->created_at = Carbon::now();
            $model->save();

            DB::commit();

            return $this->jsonReturns(10000, $this->success, null, 'create');
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->jsonReturns(50000, $e->getMessage(), null, 'create');
        }
    }

    // 配置源列表-type=0=正常数据，1=历史数据
    public function sourceListConfig($input)
    {
        $page = (int)($input['page'] ?? 1);
        $limit = $input['limit'] ?? $this->limit;
        $offest = ($page - 1) * $limit;
        // 关键字
        $keyword = $input['keyword'] ?? '';
        // 数据类型
        $type = $input['type'] ?? 0;

        $where = null;
        $where[] = ['is_removed', '=', $type, 'AND'];
        // 快捷搜索
        if ($keyword) {
            $where[] = ['key_name', 'like', "%{$keyword}%", 'AND'];
            $where[] = ['key_title', 'like', "%{$keyword}%", 'OR'];
        }

        $totalCount = ZhihuConfigSource::where($where)->count();
        $listData = ZhihuConfigSource::where($where)
            ->offset($offest)
            ->limit($limit)
            ->get()
            ->toArray();

        $jsonData = ['list' => $listData, 'count' => $totalCount];

        return $this->jsonReturns(10000, $this->success, $jsonData, 'list');
    }

    // 系统配置设置
    public function setting(Request $request, $key)
    {
        // key值配置校验
        if (!$config = static::checkSystemKey($key)) {
            return $this->jsonReturns(99999, trans('zhihu.Illegal-Parameter-No-Config-Set', ['key' => $key]), null, 'verror');
        }

        // 参数校验及过滤, originParam参数备用-原始参数
        $param = static::systemsConfigCheck($config, $request->all(), $originParam);
        // 保存失败
        if (!static::settingSave($key, $param)) {
            return $this->jsonReturns(50000, $this->error, null, 'save');
        }

        return $this->jsonReturns(10000, $this->success, null, 'save');
    }

    // 系统配置获取
    public function gettingByKey(Request $request, $key)
    {
        // key值配置校验
        if (!$config = static::checkSystemKey($key)) {
            return $this->jsonReturns(99999, trans('zhihu.Illegal-Parameter-No-Config-Set', ['key' => $key]));
        }
        $jsonData = static::getting($key);

        return $this->jsonReturns(10000, $this->success, is_null($jsonData) ? [] : $jsonData);
    }

    // 通过key获取值
    public static function getting($key)
    {
        $model = ZhihuSystemConfig::where('k', $key)->firstOr(function () {
            return null;
        });

        if (!is_null($model)) {
            $v = $model->v;
            return unserialize($v);
        }
    }

    // 系统配置数据保存
    public static function settingSave($key, $data)
    {
        $model = ZhihuSystemConfig::where('k', $key)->first();
        if (empty($model)) {
            $model = new ZhihuSystemConfig;
            $model->k = $key;
            $model->created_at = Carbon::now();
        } else {
            $model->updated_at = Carbon::now();
        }

        $model->v = serialize($data);

        return $model->save();
    }

    // 校验key
    public static function checkSystemKey($key) {
        return ZhihuConfigSource::where('key_name', $key)->where('is_removed', 0)->first();
    }

    // 数据根据配置过滤参数及校验
    public static function systemsConfigCheck(&$config, $data, &$originParam)
    {
        $originParam = $data;
        $keyArr = Str::of(rtrim($config['key_field'], ','))->explode(',')->toarray();
        if (!Arr::has($data, $keyArr)) {
            throw new \Exception(trans('zhihu.The-Dirty-System-Config-Lost-Parmeter'));
        }

        return Arr::only($data, $keyArr);
    }
}
